package com.sharemarking.application.common.controller;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.sharemarking.application.common.entity.User;
import com.sharemarking.application.common.repository.UserRepo;
import com.sharemarking.application.common.util.SmsDemo;

@Controller
@RequestMapping("pwd")
public class PwdController {
	
	@Autowired
	private UserRepo mr;
	
	@RequestMapping(value="resetPwd",method=RequestMethod.GET)
	public void resetPwd(){
	}
	
	/*@RequestMapping(value="resetPwd",method=RequestMethod.POST)
	public String resetPwd(String loginName,String validateCode,HttpSession session) throws Exception{
		boolean valid=ms.checkResetPwdMail(loginName, validateCode);
		if(!valid)return "redirect:resetPwd?error";
		session.setAttribute("resetPwd", loginName);
		return "redirect:newPwd";
	}*/
	
	/*@RequestMapping(value="sendValidateCode",method=RequestMethod.POST)
	@ResponseBody
	public void sendValidateCode(String loginName){
		ms.sendResetPwdMail(mr.findByLoginName(loginName));
	}*/
	
	@RequestMapping(value="newPwd",method=RequestMethod.GET)
	public void newPwdGet(){
		
	}
	
	@RequestMapping(value="newPwd",method=RequestMethod.POST)
	@Transactional
	public String newPwdPost(String newPwd,HttpSession session,RedirectAttributes redirectAttributes) throws NoSuchAlgorithmException{
		String loginName=(String)session.getAttribute("resetPwd");
		System.out.println(loginName);
		if(!StringUtils.isEmpty(loginName)){
			
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(newPwd.getBytes());
			
			String pwd = new BigInteger(1,md.digest()).toString(16);
			mr.findByLoginName(loginName).setPassword(pwd);
			
			
		}
		redirectAttributes.addFlashAttribute("valid", !StringUtils.isEmpty(loginName));
		return "redirect:result";
	}
	
	@RequestMapping(value="result",method=RequestMethod.GET)
	public void result(){
		
	}
	
	//发送验证码
	@RequestMapping(value="rePassword")
	@ResponseBody
	public String rePassword(String mobile,String password,String code,HttpServletResponse res) throws ClientException, InterruptedException{
	//	SmsDemo sd=new SmsDemo();
	//	sd.sendSms(mobile);
		System.out.println("mobile:"+mobile);
		/**设置响应头允许ajax跨域访问**/
		res.setHeader("Access-Control-Allow-Origin","*");
		
		String result = "";
        //发短信
        SendSmsResponse response = SmsDemo.sendSms(mobile);
        //返回的验证码phoneNum
        String phoneNum=SmsDemo.getPhoneNum();
        
        System.out.println("code:+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"+code);
        
        System.out.println("phoneNum===================================================:"+phoneNum);
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=======================================" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());

        Thread.sleep(3000L);

        //查明细
        if(response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = SmsDemo.querySendDetails(response.getBizId(),mobile);
            System.out.println("短信明细查询接口返回数据----------------");
            System.out.println("Code=" + querySendDetailsResponse.getCode());
            System.out.println("Message=" + querySendDetailsResponse.getMessage());
            int i = 0;
            for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
            {
                System.out.println("SmsSendDetailDTO["+i+"]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
                
            }
            System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
            System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
            
            return phoneNum;
            
        }
        result="false";
        
        return result;
	}
	
	//验证手机号码是否存在
	@RequestMapping(value="checkMobile")
	@ResponseBody
	public String checkMobile(String mobile,HttpServletResponse res,HttpServletRequest req){
			/**设置响应头允许ajax跨域访问**/
		   res.setHeader("Access-Control-Allow-Origin","*");
		   System.out.println("mobile+++++++++++++++++++++++:"+mobile);
		   String result="";
		   User user=mr.findByMobile(mobile);
		   
		   if(user!=null){
			   result="true";
			   return result;
		   }
		   result="false";
		   return result;
	}
	
	//检验验证码是否正确
	@RequestMapping(value="checkCode")
	@ResponseBody
	public String checkCode(String code,HttpServletResponse res){
		/**设置响应头允许ajax跨域访问**/
	    res.setHeader("Access-Control-Allow-Origin","*");
		String result="";
		//返回的验证码phoneNum
        String phoneNum=SmsDemo.getPhoneNum();
        System.out.println("code:"+code);
        System.out.println("phoneNum:"+phoneNum);
        
        if(code.equals(phoneNum)){
        	result="true";
        }else{
        	result="false";
        }
        return result;
	}
	
	//重设密码
	@RequestMapping(value="resetPassword")
	@ResponseBody
	public String resetPwd(String password,String mobile,HttpServletResponse res) throws NoSuchAlgorithmException{
		/**设置响应头允许ajax跨域访问**/
	    res.setHeader("Access-Control-Allow-Origin","*");
		User user=mr.findByMobile(mobile);
		System.out.println("user:"+user);
		System.out.println("password:"+password);
		System.out.println("mobile:"+mobile);
		
		if(user!=null){
			MessageDigest md = MessageDigest.getInstance("MD5");
		    md.update(password.getBytes());
			
			String pwd = new BigInteger(1,md.digest()).toString(16);
		    user.setPassword(pwd);
			mr.save(user);
			System.out.println("重置密码好了");
		 
		}
		return "redirect:index";
	}
}
